package service

import (
	"go-im/src/helper"
	"go-im/src/model"
	"net/http"

	"github.com/gin-gonic/gin"
)

func RoomComplete(c *gin.Context) {
	// 从 user_claims 获取当前用户信息
	uc := c.MustGet("user_claims").(*helper.UserClaim)

	// 获取房间身份
	roomId := c.Query("roomId")
	if roomId == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"msg":  "missing roomId parameter",
		})
		return
	}

	// 绑定请求数据到结构体
	var req struct {
		Number string `json:"number" binding:"omitempty"`
		Name   string `json:"name" binding:"omitempty"`
		Info   string `json:"info" binding:"omitempty"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"msg":  "invalid request data: " + err.Error(),
		})
		return
	}

	// 检查用户是否有权限编辑房间
	if !model.UserHasRoomAccess(uc.Identity, roomId) {
		c.JSON(http.StatusForbidden, gin.H{
			"code": -1,
			"msg":  "no permission to edit this room",
		})
		return
	}

	// 更新房间信息
	err := model.UpdateRoomInfo(roomId, req.Number, req.Name, req.Info)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": -1,
			"msg":  "failed to update room info: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "room info updated successfully",
	})
}
